package com.zackeus.xupdate.widget;

import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.ColorInt;
import androidx.annotation.DrawableRes;

import com.zackeus.common.utils.ColorUtils;
import com.zackeus.common.utils.ConvertUtils;
import com.zackeus.common.utils.DrawableUtils;
import com.zackeus.xupdate.R;
import com.zackeus.xupdate.XUpdate;
import com.zackeus.xupdate.entity.LibraryUpdateEntity;
import com.zackeus.xupdate.factory.impl.DefaultUpdateDownloader;
import com.zackeus.xupdate.utils.Utils;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 版本更新提示器
 * @name: DefaultUpdateActivity
 * @author: zz
 * @date: 2022/12/6
 */
public class DefaultUpdateActivity extends BaseUpdateActivity<DefaultUpdateDownloader> implements View.OnClickListener {

    //======顶部========//
    /* 顶部图片 */
    private ImageView mIvTop;
    /* 标题 */
    private TextView mTvTitle;

    //======更新内容========//
    /* 版本更新内容 */
    private TextView mTvUpdateInfo;
    /* 版本更新 */
    private Button mBtnUpdate;
    /* 忽略版本 */
    private TextView mTvIgnore;
    /* 进度条 */
    private NumberProgressBar mNumberProgressBar;

    //======底部========//
    /* 底部关闭 */
    private LinearLayout mLlClose;
    private ImageView mIvClose;

    @Override
    protected int initContentView(Bundle savedInstanceState) {
        return R.layout.default_update_activity;
    }

    @Override
    protected DefaultUpdateDownloader initDownLoader() {
        return new DefaultUpdateDownloader();
    }

    @Override
    protected void initData(Bundle bundle) {
        super.initData(bundle);

        // 顶部图片
        mIvTop = findViewById(R.id.iv_top);
        // 标题
        mTvTitle = findViewById(R.id.tv_title);
        // 提示内容
        mTvUpdateInfo = findViewById(R.id.tv_update_info);
        // 更新按钮
        mBtnUpdate = findViewById(R.id.btn_update);
        // 忽略
        mTvIgnore = findViewById(R.id.tv_ignore);
        // 进度条
        mNumberProgressBar = findViewById(R.id.npb_progress);
        // 关闭按钮+线 的整个布局
        mLlClose = findViewById(R.id.ll_close);
        // 关闭按钮
        mIvClose = findViewById(R.id.iv_close);
        /* 点击监听 */
        mBtnUpdate.setOnClickListener(this);
        mIvClose.setOnClickListener(this);
        mTvIgnore.setOnClickListener(this);

        /* 设置主题色 */
        initTheme(promptEntity.getThemeColor(), promptEntity.getTopResId(), promptEntity.getButtonTextColor());
        if (updateEntity != null) {
            initUpdateInfo(updateEntity);
        }
    }

    @Override
    public void onClick(View view) {
        int i = view.getId();

        /* 点击关闭按钮 */
        if (i == R.id.iv_close) {
            this.downLoader.cancelDownload();
            dismissDialog();
            return;
        }

        /* 点击忽略按钮 */
        if (i == R.id.tv_ignore) {
            ignoreVersion();
            return;
        }

        /* 点击版本升级按钮 */
        if (i == R.id.btn_update) {
            /* 忽略版本在点击更新按钮后隐藏 */
            if (updateEntity.isIgnorable()) {
                mTvIgnore.setVisibility(View.GONE);
            }
            /* 安装APK */
            installApp();
        }
    }

    @Override
    protected void onDownloadStart() {
        super.onDownloadStart();
        if (!isFinishing()) {
            mNumberProgressBar.setVisibility(View.VISIBLE);
            mNumberProgressBar.setProgress(0);
            mBtnUpdate.setVisibility(View.GONE);
        }
    }

    @Override
    protected void onDownloadProgress(long progress, long total) {
        super.onDownloadProgress(progress, total);
        if (!isFinishing()) {
            int rate = 0;
            if (total != 0) {
                BigDecimal p = new BigDecimal(progress);
                BigDecimal t = new BigDecimal(total);
                rate = p.multiply(new BigDecimal(100)).divide(t, RoundingMode.HALF_UP).intValue();
            }

            mNumberProgressBar.setProgress(rate);
            mNumberProgressBar.setMax(100);
        }
    }

    @Override
    protected void onInstallError(Throwable throwable) {
        super.onInstallError(throwable);
        if (!isFinishing()) {
            if (updateEntity.isForce() || promptEntity.isIgnoreDownloadError()) {
                /* 如果是强制更新的话，默认设置是否忽略下载异常为true，保证即使是下载异常也不退出提示 */
                refreshUpdateButton();
            } else {
                dismissDialog();
            }
        }
    }

    /**
     * 初始化更新信息
     * @param updateEntity 更新信息
     */
    private void initUpdateInfo(LibraryUpdateEntity updateEntity) {
        // 弹出对话框
        final String newVersion = updateEntity.getVersionName();
        String updateInfo = Utils.getDisplayUpdateInfo(this, updateEntity);
        // 更新内容
        mTvTitle.setText(String.format(getString(R.string.xupdate_lab_ready_update), newVersion));
        mTvUpdateInfo.setText(updateInfo);

        // 刷新升级按钮显示
        refreshUpdateButton();

        // 强制更新,不显示关闭按钮
        if (updateEntity.isForce()) {
            mLlClose.setVisibility(View.GONE);
        }
    }

    /**
     * 初始化主题色
     */
    private void initTheme(@ColorInt int themeColor, @DrawableRes int topResId, @ColorInt int buttonTextColor) {
        if (themeColor == -1) {
            themeColor = ColorUtils.getColor(R.color.xupdate_default_theme_color);
        }
        if (topResId == -1) {
            topResId = R.drawable.dialog_bg_top;
        }
        if (buttonTextColor == 0) {
            buttonTextColor = ColorUtils.isColorDark(themeColor) ? Color.WHITE : Color.BLACK;
        }
        setDialogTheme(themeColor, topResId, buttonTextColor);
    }

    /**
     * 设置
     *
     * @param themeColor 主题色
     * @param topResId   图片
     */
    private void setDialogTheme(int themeColor, int topResId, int buttonTextColor) {
        // TODO: 2022/11/21 优化Drawable设置
//        Drawable topDrawable = _XUpdate.getTopDrawable(mPromptEntity.getTopDrawableTag());
//        if (topDrawable != null) {
//            mIvTop.setImageDrawable(topDrawable);
//        } else {
//            mIvTop.setImageResource(topResId);
//        }
        mIvTop.setImageResource(topResId);

        mBtnUpdate.setBackground(DrawableUtils.getDrawable(ConvertUtils.dp2px(4), themeColor));
        mNumberProgressBar.setProgressTextColor(themeColor);
        mNumberProgressBar.setReachedBarColor(themeColor);
        mBtnUpdate.setTextColor(buttonTextColor);
    }

    /**
     * 刷新升级按钮显示
     */
    private void refreshUpdateButton() {
        mNumberProgressBar.setVisibility(View.GONE);
        mBtnUpdate.setText(XUpdate.with().encryptor().isFileValid(updateEntity) ? R.string.xupdate_lab_install : R.string.xupdate_lab_update);
        mBtnUpdate.setVisibility(View.VISIBLE);
        mTvIgnore.setVisibility(updateEntity.isIgnorable() ? View.VISIBLE : View.GONE);
    }

}
